package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Great;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IGreatService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/greats")
public class GreatController {
    @Autowired
    private IGreatService greatService;
    @Autowired
    private ITravelService travelService;
    //点赞操作
    @PostMapping
    public Object great(Long travelId){
        JSONResult jsonResult = new JSONResult();
            try {
                //首先查询点赞记录是否存在该用户的记录
                //得到当前用户的id
                User user = UserContext.getCurrentUser();
                if (user==null){
                    jsonResult.setMsg("您未登录");
                    jsonResult.setSuccess(false);
                    return jsonResult;
                }
                Long userId = user.getId();
                Great great=greatService.get(userId,travelId);
                //如果great为!null就是取消点赞操作,否则就是点赞操作
                if (great !=null){
                    //取消点赞,删除点赞记录,同时改文章的点赞数量减一
                    greatService.deleteGreat(userId,travelId);
                    travelService.subGreatNum(travelId);
                }else {
                    //增加一条点赞记录
                    great = new Great();
                    great.setUser(user);
                    Travel travel = new Travel();
                    travel.setId(travelId);
                    great.setTravel(travel);
                    greatService.insertGreat(great);
                    //并且该文章的点赞数量加一
                    travelService.addGreatNum(travelId);
                }
        }catch (Exception e){
            e.printStackTrace();
            jsonResult.setMsg(e.getMessage());
        }
        return jsonResult;
    }

    @GetMapping("/{id}")
    public Object get(@PathVariable Long id){
        User user = UserContext.getCurrentUser();
        Great great = null;
        if (user!=null){
             great= greatService.get(user.getId(), id);
        }
        return great;
    }
}
